import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wanAndroid/bean/wen_da_model.dart';
import 'package:wanAndroid/common/http/http_service.dart';
import 'package:wanAndroid/common/http/http_uts.dart';
import 'package:wanAndroid/common/uts/ui_uts.dart';
import 'package:wanAndroid/res/colors.dart';
import 'package:wanAndroid/widget/wen_da_item_view.dart';

class PageWenDa extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageWenDa();
}

class _PageWenDa extends State<PageWenDa> {
  RefreshController _refreshController;
  int _currPage = 1;
  int _pageCount = 0;
  var wendaDatas = <WenDaDatas>[];

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: true);
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        backgroundColor: ResColors.scaffoldColor,
        appBar: UiUts.NoTitlebar(),
        body: SmartRefresher(
          onRefresh: () async {
            setState(() {
              _currPage = 1;
            });
            getData();
          },
          onLoading: () async {
            if (_currPage == _pageCount) return;
            setState(() {
              _currPage += 1;
            });
            getData();
          },
          enablePullUp: true,
          enablePullDown: true,
          header: ClassicHeader(),
          footer: ClassicFooter(),
          controller: _refreshController,
          child: wendaDatas.isEmpty
              ? UiUts.getEmpty()
              : ListView.builder(
                  itemBuilder: (context, index) {
                    final WenDaDatas item = wendaDatas[index];
                    return WenDaItemView(item);
                  },
                  itemCount: wendaDatas.length,
                  scrollDirection: Axis.vertical,
                ),
        ),
      );

  ///获取数据
  Future<void> getData() async {
    WenDaModel bean;
    HttpService.wenda(
      _currPage,
      HttpCallback((response) {
        UiUts.finishRefresh(_refreshController);

        ///请求成功
        bean = WenDaModel.fromJson(response.data);
        if (HttpUts.isSuccess(bean.errorCode)) {
          if (_currPage == 1) {
            setState(() {
              wendaDatas = bean.data.datas;
              _pageCount = bean.data.total;
            });
          } else {
            setState(() {
              _pageCount = bean.data.total;
              wendaDatas.addAll(bean.data.datas);
            });
          }
        }
      }, (e) {
        UiUts.finishRefresh(_refreshController);

        ///异常处理
      }),
    );
  }
}
